package com.maas.util.mybatis.jpa.littlenb.conditions.plus.core.tools;


import com.maas.util.mybatis.jpa.littlenb.common.JpaTools;
import com.maas.util.mybatis.jpa.littlenb.common.db.JbaDbPluginConst;
import com.maas.util.mybatis.jpa.littlenb.conditions.plus.core.query.QueryWrapper;

/**
 * <p>
 * DbSearchUtil
 * </p>
 *
 * @author zxm
 * @date 2021/01/07 16:49
 * @since 2021/01/07 16:49
 */
public class DbSearchUtil {
    public static String DATE_COL = "create_time";


    public static void timePeriodQuery(QueryWrapper wrapper, DateSearchDtoInf dto, String colName) {
        timePeriodQuery( wrapper,  dto,  colName, JbaDbPluginConst.DIALECT_CURR);
    }

    /**
     * 时间查询-条件构造
     * @param dto  DateSearchDto implements DateSearchDtoInf
     * @param colName
     * @param dbDialect 数据库方言（Oracle，MySQL，MS SQL Serve） JbaDbPluginConst.DIALECT_xxx/JbaDbPluginConst.getDialectCurr()
     */
    public static void timePeriodQuery(QueryWrapper wrapper, DateSearchDtoInf dto, String colName, String dbDialect) {

        /**
         * mysql
         */
        if(JpaTools.isEmpty(dbDialect)|| JbaDbPluginConst.DIALECT_MYSQL.equals(dbDialect)){
            // 查询时间起
            wrapper.apply(dto.getBeginDate() != null,
                    "DATE_FORMAT( "+colName+", '%Y-%m-%d' ) " +
                            " >= DATE_FORMAT( '"+ dto.getBeginDate() +"', '%Y-%m-%d' )");

            // 查询时间止
            wrapper.apply(dto.getEndDate() != null,
                    "DATE_FORMAT( "+colName+", '%Y-%m-%d' ) " +
                            " <= DATE_FORMAT( '"+dto.getEndDate()+"', '%Y-%m-%d' )");
        }

        /**
         * oracle
         */
        if(JpaTools.isEmpty(dbDialect)|| JbaDbPluginConst.DIALECT_ORACLE.equals(dbDialect)){
            // 查询时间起
            wrapper.apply(dto.getBeginDate() != null,
                    "to_char( "+colName+", 'yyyy-mm-dd' ) " +
                            " >= to_char( '"+ dto.getBeginDate() +"', 'yyyy-mm-dd' )");

            // 查询时间止
            wrapper.apply(dto.getEndDate() != null,
                    "to_char( "+colName+", 'yyyy-mm-dd' ) " +
                            " <= to_char( '"+dto.getEndDate()+"', 'yyyy-mm-dd' )");
        }
    }

    /**
     * 合并字段
     * @param colName
     * @param dbDialect
     * @return
     */
    public static String groupConcat(String colName, String dbDialect) {
        /**
         * mysql
         */
        if(JpaTools.isEmpty(dbDialect)||JbaDbPluginConst.DIALECT_MYSQL.equals(dbDialect)){
            return "GROUP_CONCAT( "+colName+" )";
        }
        return "";
    }

    public static boolean isMySql(String dbDialect) {
        if(JpaTools.isEmpty(dbDialect)||JbaDbPluginConst.DIALECT_MYSQL.equals(dbDialect)){
            return true;
        }else {
            return false;
        }
    }
}
